<?php

namespace App\Console\Commands\OpenShop;

use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderToCollection;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ImportHistoryOrder extends Command
{
    public static string $errOrders     = "";
    public static string $noticeOrders  = "";
    public static string $successOrders = "";

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:import-history-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开店 : 导入历史开店订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址 : ');

        if (config('app.env') == 'qa' || config('app.env') == 'dev') {
            if (!$url) {

                // 正式表格
            $url = 'https://file.51kuafu.com/cf/b5/19f8cbf889a4b2e783ca50f8375144b608c293ec9825ac93a7befc3d21e3.xlsx';
//                $url = 'https://file.51kuafu.com/44/d3/bc09c486c36cc024ca48cdc25d20e32ad4cb052c264ef344071bb7251999.xlsx';

                $this->info('没输入excel地址，qa环境，执行默认的excel:' . $url);
            }
        }

        $pathInfo = parse_url($url);
        $client   = new Client();
        $tempData = $client->request("get", $url)->getBody()->getContents();
        $file     = md5($url) . date('YmdHis', time()) . "." . implode(".", $pathInfo)[1];
        Storage::disk("public")->put($file, $tempData);
        $import = Excel::toCollection(null, storage_path("app/public") . "/{$file}");
        Storage::disk("public")->delete($file);

        $import = $import->first()->filter(function ($item) {
            if ($item[0] === null) {
                return false;
            }

            return true;
        });

        Log::info("ImportHistoryOrder import", $import->toArray());

        (new HistoryOrderToCollection)->collection($import, $this);
    }
}
